﻿using System;
using System.Drawing;
using System.Diagnostics;
using System.Collections.Generic;

using Microsoft.WindowsMobile.Status;

using iPhoneUI.Shell;

namespace iPhoneUI.Widgets
{
    public class Badge : TextWidget
    {
        private IImage m_badgeImage;
        private SystemProperty m_systemProperty;

        public Badge()
        {
            Font = ShellConfig.CreateFont(9, FontStyle.Bold);
            m_badgeImage = ShellConfig.CreatePerPixelAlphaImage("Badge1-RED.png");
        }

        protected override void OnSetOwner()
        {
            SetInitialSize(new Size(30, 30));
            base.OnSetOwner();
        }

        public override void LayoutAsDecoration(Rectangle reference)
        {
            Location = new Point(reference.X + 30, reference.Y - 10);
        }

        public SystemProperty SystemProperty
        {
            get
            {
                return m_systemProperty;
            }
            set
            {
                if (m_systemProperty != value)
                {
                    m_systemProperty = value;
                    using (SystemState state = new SystemState(m_systemProperty, true))
                    {
                        if (state.CurrentValue != null)
                            Count = (int)state.CurrentValue;

                        RegisterSystemStateChange(m_systemProperty);
                    }
                }
            }
        }

        public int Count { get; set; }

        protected override void OnDispose()
        {
            m_badgeImage = null;

            base.OnDispose();
        }

        protected override void OnSystemStateChanged(SystemState property, object newValue)
        {
            if (newValue != null)
                Count = Convert.ToInt32(newValue);

            base.OnSystemStateChanged(property, newValue);
        }

        protected override void OnDraw(Canvas canvas, Rectangle clipBounds)
        {
            if (Count > 0)
            {
                canvas.AlphaBlend(m_badgeImage, ClientArea);
                using (StringFormat format = new StringFormat(StringFormatFlags.NoClip))
                using (Brush b = new SolidBrush(ForeColor))
                {
                    format.Alignment = StringAlignment.Center;
                    format.LineAlignment = StringAlignment.Center;
                    RectangleF rect = new RectangleF(ClientArea.X, ClientArea.Y - 3, ClientArea.Width, ClientArea.Height);
                    canvas.DrawString(Count.ToString(), Font, b, rect, format);
                }
            }
        }
    }
}
